import React, { Component, Suspense } from 'react';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import PageLoading from "@/components/PageLoading";
import { connect } from 'dva';
import { Card, Tabs, Button, Form, Modal, Input, Icon, message } from 'antd';
import styles from './index.less';
import RejectionList from './list';
import { getCategoryList, getCategoryRemove, postCategoryAdd, postCategoryUpdate } from '@/services/secureRejection';
import { formatMessage } from 'umi-plugin-react/locale';
const { TabPane } = Tabs;
let sortCount;

class questionRejection extends Component {
	constructor(props) {
		super(props);
		this.state = {
			sortVisible: false,
			sortTabList: [],
			sortList: [],
			sortActive: [],
		};
	}

	componentDidMount() {
		this.sortList()
	}

	sortList = async () => {
		let res = await getCategoryList({ type: '0' });
		this.setState({ sortTabList: res, })
	}

	sortManagement = async () => {
		let res = await getCategoryList({ type: '0' });
		sortCount = res?.length;
		this.setState({ sortVisible: true, sortList: res?.map(item => ({ ...item, isAdd: false })), })
	}

	sortCancel = () => {
		this.setState({ sortVisible: false })
	}

	sortValueInput = ({ target: { value } }, index) => {
		let { sortList } = this.state;
		sortList[index].name = value;
		this.setState({ sortList })
	}

	addSort = e => {
		e.stopPropagation();
        e.preventDefault();
		let { sortList, sortActive } = this.state;
		let count = sortCount++;
		sortList.push({ name: '', id: count, isAdd: true });
		sortActive.push(count);
		this.setState({ sortList, sortActive });
	}

	editSort = (sort, index) => {
		let { sortActive } = this.state;
		if (sortActive.indexOf(index) > -1) { } else {
			sortActive.push(index)
		};
		this.setState({ sortActive });
	}

	delSort = (sort, index) => {
		let { sortList } = this.state;
		Modal.confirm({
			content: formatMessage({ id: 'largeModelCenter.secureRejection.questionRejection.confirmDeleteCategory' }),
			okText: formatMessage({ id: 'largeModelCenter.secureRejection.questionRejection.delete' }),
			okType: 'danger',
			cancelText: formatMessage({ id: 'largeModelCenter.secureRejection.questionRejection.cancel' }),
			maskStyle: { zIndex: 99999 },
			zIndex: 999999,
			onOk: async () => {
				let res = await getCategoryRemove({ id: sort.id });
				console.log(res);
				if (res.code === 0) {
					message.info(formatMessage({ id: 'largeModelCenter.secureRejection.questionRejection.operationSuccess' }))
					let list = sortList.filter(s => s.id !== sort.id);
					this.setState({ sortList: list }, () => this.sortList());
				}
			},
			onCancel() {
				console.log('Cancel');
			},
		});
	}

	submitEditSort = async (sort, index) => {
		let { sortList } = this.state;
		let res = { code: -1, data: false, message: formatMessage({ id: 'largeModelCenter.secureRejection.questionRejection.operationFailed' }) }; 
		if (sort.isAdd) {
			res = await postCategoryAdd({ name: sort.name, type: '0' });
		} else {
			res = await postCategoryUpdate({ id: sort.id, name: sort.name, type: '0' });
		};
		console.log(res);
		if (res.code === 0 && res.data) {
			message.info(formatMessage({ id: 'largeModelCenter.secureRejection.questionRejection.saveSuccess' })); 
			sortList[index].id = res.data;
			sortList[index].isAdd = false;
			this.setState({ sortList }, () => this.sortList());
		};
	}

	cancelEditSort = (sort, index) => {
		if (sort.isAdd) {
			let { sortList } = this.state;
			sortList = sortList.filter(i => i != sort);
			this.setState({ sortList });
		} else {
			let { sortActive } = this.state;
			if (sortActive.indexOf(index) > -1) {
				sortActive = sortActive.filter(i => i != index)
			};
			this.setState({ sortActive });
		}
	}

	render() {
		const { sortVisible, sortTabList, sortList, sortActive } = this.state;
		const operations = (
			<span>
				<Button style={{ marginRight: 12 }} icon='bars' onClick={this.sortManagement}>{formatMessage({ id: 'largeModelCenter.secureRejection.questionRejection.categoryManagement' })}</Button>
				{/* <Button icon='tag' onClick={this.tagManagement}>标签管理</Button> */}
			</span>
		);

		return (
			<Suspense fallback={<PageLoading />}>
				<PageHeaderWrapper>
					<Card bordered={false} style={{background:"unset"}}>
						<Tabs tabBarExtraContent={operations}>
							<TabPane tab={formatMessage({ id: 'largeModelCenter.secureRejection.questionRejection.all' })} key="all">
								<RejectionList onRef={ref => this.RejectionRef = ref} categoryId={undefined} categoryList={sortTabList} />
							</TabPane>
							{sortTabList && sortTabList.length > 0 ? sortTabList.map((sort, index) => {
								return (
									<TabPane tab={sort.name} key={sort.id}>
										<RejectionList onRef={ref => this.RejectionRef = ref} categoryId={sort.id} categoryList={sortTabList} />
									</TabPane>
								)
							}) : null}
						</Tabs>
					</Card>
					<Modal title={formatMessage({ id: 'largeModelCenter.secureRejection.questionRejection.categoryManagement' })} onCancel={this.sortCancel} visible={sortVisible} destroyOnClose footer={null}>
						<div className={styles["tabManagement"]}>
							{sortList.map((item, index) => {
								return (
									<div key={index} style={{ display: 'flex', alignItems: 'center', gap: '12px', marginBottom: 12 }}>
										{sortActive && sortActive.length > 0 && sortActive.indexOf(item.id) > -1 ? (
											<>
												<Input style={{ flex: 1 }} value={item.name} onChange={e => this.sortValueInput(e, index)} />
												<Button type="primary" onClick={() => this.submitEditSort(item, index)}>保存</Button>
												<Button onClick={() => this.cancelEditSort(item, item.id)}>取消</Button>
											</>
										) : (
											<>
												<span style={{ flex: 1, background: '#F2F2F2', padding: '4px 12px', lineHeight: '24px', borderRadius: '3px' }}>{item.name}</span>
												<Icon type="form" onClick={() => this.editSort(item, item.id)} />
												<Icon type="close" onClick={() => this.delSort(item, item.id)} />
											</>
										)}
									</div>
								)
							})}
							<Button type="link" icon="plus" onClick={this.addSort}>添加分类</Button>
						</div>
					</Modal>
				</PageHeaderWrapper>
			</Suspense>
		);
	}
}

export default questionRejection;
